package com.neo.controller;

import com.alibaba.fastjson.JSONObject;
import com.jfinal.aop.Before;
import com.jfinal.aop.Clear;
import com.jfinal.aop.Inject;
import com.jfinal.core.Controller;
import com.jfinal.kit.HashKit;
import com.neo.interceptor.loginInterceptor;
import com.neo.model.SysUser;
import com.neo.util.MyCookie;
import netscape.javascript.JSObject;
import org.eclipse.jetty.util.ajax.JSONObjectConvertor;

import java.util.List;

public class loginModel extends Controller {

    private static final String SESSION_VlUES = "LI_YANG_NEO";

    @Inject
    SysUser sysUser;

    @Clear(loginInterceptor.class)
    public void index(){
        //默认访问登录页
        renderFreeMarker("login.html");
    }
    //登录页跳转到注册页
    public void goRegister(){
        renderFreeMarker("register.html");
    }

    //注册成功跳转到登陆页面
    public void loginSuccess(){
        renderFreeMarker("login.html");
    }
//注册
    public  void  register(){
        String userName = getPara("userName");
        SysUser all = SysUser.sysUser.findFirst("select * from sys_user where userName='"+userName+"'");
        System.out.println("all="+all);
        if (all==null){
            //这里可以使用链式 写法 节省代码 getModel().save
            SysUser sysItem = getModel(SysUser.class,"user");
            sysItem.save();
            System.out.println(" 注册成功");

//          返回值只会执行一个 比如如下 有两个render  顺序为从上之下执行 会执行redirect 而不会执行renderText
            renderText(" 注册成功");
            redirect("/halo/loginSuccess");
        }else {

            //注册这里的错误 除了这种情况 还要考虑用户进行输入的错误 如果未错误的数据类型 直接进入数据库中会报错
//            二为 网络错误 如果发现了网络错误 也会导致数据库中出现错误数据 并报错

            renderText("用户名已存在");
        }
    }


    //主页
    public void homepage(){
        renderFreeMarker("manage.html");
    }
    //登陆
    public  void login(){
        String userName = getPara("userName");
        String passWord = getPara("passWord");

        if(userName!=null){
               SysUser sysUser = SysUser.sysUser.findFirst("select * from sys_user where userName='" + userName + "'");
            if (sysUser == null || sysUser._getAttrsEntrySet().size() == 0){
                JSONObject jo=new JSONObject();
                jo.put("code","-1");
                jo.put("message","该用户不存在，请去注册页面注册");
                renderJson(jo);
                return;
            }
            System.out.println(sysUser);
            if(passWord.equals(sysUser.get("passWord"))){
/*                setCookie(MyCookie.getCookieKey(), MyCookie.getCookie(), 600);*/
                setSessionAttr("userName",userName);
                redirect("/findAll");
            }else{
                setAttr("msg" , "密码错误");
                renderFreeMarker("login.html");
            }
        }else{
            setAttr("msg" , "账号不存在！！");
            renderFreeMarker("login.html");
        }
    }



}
